package com.example.asapp.base;

import com.example.asapp.annotation.HasLogin;
import com.example.asapp.exception.AuthUnexpectException;
import com.example.asapp.user.detail.Detail;
import com.example.asapp.user.detail.DetailDao;
import com.example.asapp.user.role.RoleDao;
import com.example.asapp.util.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BaseService {
    @Autowired
    RedisService redisService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    DetailDao detailDao;

    @HasLogin
    public UserInfoBase getBaseUserInfo() {
        UserInfo userInfo = new UserInfo();

        String id = request.getHeader("id");

        log.info("login user id is:{}", id);
        Detail detail = detailDao.findById(id).get();
        log.info("id is{}", detail);

        userInfo.setName(detail.getName());
        return userInfo;
    }

    @HasLogin
    public UserInfo getUserInfo(){
        UserInfo userInfo=new UserInfo();

        String token=request.getHeader("token");
        String id=request.getHeader("id");

        log.info("login user id is:{}",id);
        Detail detail=detailDao.findById(id).get();
        log.info("id is{}",detail);

        userInfo.setName(detail.getName());
        userInfo.setLogin(true);
        userInfo.setToken(token);
        userInfo.setDetail(detail);
        userInfo.setRoleList(detail.getRoleList());
        List<String> roleValueList=detail.getRoleList().stream().map(e->{
            return e.getValue();
        }).collect(Collectors.toList());
        userInfo.setRoles(roleValueList);
        userInfo.setOptions(getOptions());
        return userInfo;
    }

    private HashMap<String, Object> getOptions() {

        HashMap<String,Object> map=new HashMap<>();
        map.put("roles",roleDao.findAll());
        return map;
    }

    @Autowired
    RoleDao roleDao;

    public String getUserId(){
        return (String) redisService.get(request.getHeader("token"));
    }

    public Boolean getLogin() {

        if(
                request.getHeader("token").equals("") || ("").equals(request.getHeader("token"))
                        ||request.getHeader("id").equals("") || ("").equals(request.getHeader("id"))
        ){
            return false;
        }
        String id=request.getHeader("id");
        String token =request.getHeader("token");
        if(!redisService.hasKey(id)){
            return false;
        }
        return redisService.get(id).equals(token);
    }
}
